import { Button, message, Modal, Space } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'

import { cinemaApi, commonApi } from '@/apis'
import { RuleItem } from '@/apis/cinemaTypes'
import {
  type ProEditorProps,
  type ProEditorRef,
  type ProTableProps,
  type ProTableRef,
  ProEditor,
  ProTable
} from '@/components'
import { TABLE_FORMAT } from '@/constants'

export default defineComponent({
  name: 'RuleAlertManage',
  setup() {
    const dialogLoading = ref(false)
    const showDialog = ref(false)
    const sceneType = [
      '电费充值',
      '话费充值',
      '电影票',
      '腾讯视频',
      '爱奇艺',
      '芒果TV',
      '优酷视频',
      '肯德基',
      '麦当劳',
      '星巴克',
      '瑞幸咖啡',
      '金豆惠生活',
      '金豆兑好礼'
    ]
    const editorRef = ref({} as ProEditorRef)
    const editItemCur = ref({} as RuleItem)
    const editorConfig = ref({
      editorStyle: {
        height: '500px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data

              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        columns: [
          {
            title: '规则名称',
            field: 'ruleName'
          },
          {
            title: '应用场景',
            field: 'sceneType',
            formatter: ({ cellValue }) => {
              return sceneType[cellValue - 1]
            }
          },
          {
            title: '创建时间',
            field: 'createTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            slots: {
              default: 'operation'
            },
            width: 180
          }
        ],

        proxyConfig: {
          props: {
            result: 'data'
          },
          ajax: {
            query: async () => {
              const data = await cinemaApi.getRuleList()
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //编辑
    function handleEdit(item: RuleItem) {
      editItemCur.value = item
      showDialog.value = true
      editorConfig.value.editorHtml = ''
      if (item.ruleContent) {
        if (item.ruleType == 1) {
          editorConfig.value.editorHtml = `<p>${item.ruleContent}</p>`
        } else {
          editorConfig.value.editorHtml = item.ruleContent
        }
      }
      editorConfig.value.editorVisible = true
    }

    //编辑确定
    async function handleConfirm() {
      dialogLoading.value = true
      let editorData = editorRef.value.editor.getHtml()
      if (editItemCur.value.ruleType == 1) {
        editorData = editorRef.value.editor.getText()
      } else {
        editorData = editorRef.value.editor.getHtml()
      }

      try {
        await cinemaApi.editRule(editItemCur.value.id, editorData)
        await tableRef.value.table.commitProxy('query')
        showDialog.value = false
      } finally {
        dialogLoading.value = false
      }
    }

    return {
      tableRef,
      tableConfig,
      dialogLoading,
      showDialog,
      editorRef,
      editorConfig,
      handleConfirm,
      handleEdit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            // alertContent: ({ row }) => <div v-html={row.ruleContent}></div>,
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          confirmLoading={this.dialogLoading}
          v-model:visible={this.showDialog}
          width={1000}
          title={'编辑'}
          destroyOnClose
          onOk={this.handleConfirm}
        >
          <ProEditor ref="editorRef" {...this.editorConfig} />
        </Modal>
      </div>
    )
  }
})
